# Justfile for netdisk-svc CI/CD
# Usage: just <command> [args...]
# Variables can be set via environment variables or passed as arguments
#
# Note: Compilation is handled by Dockerfile (multi-stage build).
# The 'test-build' command is optional for local development/testing only.

# -----------------------------
# Default variables (can be overridden via environment or command line)
# -----------------------------
DEFAULT_BACKEND_REPO := "https://gitee.com/tjccc/go-pan.git"
DEFAULT_BACKEND_REF := "master"
DEFAULT_WORK_DIR := "./work"

DEFAULT_REGISTRY := "192.168.0.104:5000"
DEFAULT_REGISTRY_NAMESPACE := "library"
DEFAULT_BACKEND_IMAGE_NAME := "netdisk-svc"
# Note: IMAGE_TAG defaults to git commit hash if not specified
DEFAULT_IMAGE_TAG := "latest"

DEFAULT_K8S_NAMESPACE := "netdisk"
DEFAULT_RELEASE_BACKEND := "netdisk"
DEFAULT_HELM_CHART_PATH := "./helm/netdisk"
DEFAULT_KUBECONFIG_PATH := "~/.kube/config"

# Build output binary name (for local test-build only)
BINARY_NAME := "netdisk-svc"
BUILD_OUTPUT := "bin/netdisk-svc"

# -----------------------------
# Clone: Clone backend repository from Gitee
# -----------------------------
clone BACKEND_REPO='' BACKEND_REF='' WORK_DIR='':
    #!/usr/bin/env bash
    set -e
    
    # Priority: provided args (if not empty) > environment variables > defaults
    if [ -n "$BACKEND_REPO" ]; then
        FINAL_BACKEND_REPO="$BACKEND_REPO"
    else
        FINAL_BACKEND_REPO="${BACKEND_REPO:-{{DEFAULT_BACKEND_REPO}}}"
    fi
    
    if [ -n "$BACKEND_REF" ]; then
        FINAL_BACKEND_REF="$BACKEND_REF"
    else
        FINAL_BACKEND_REF="${BACKEND_REF:-{{DEFAULT_BACKEND_REF}}}"
    fi
    
    if [ -n "$WORK_DIR" ]; then
        FINAL_WORK_DIR="$WORK_DIR"
    else
        FINAL_WORK_DIR="${WORK_DIR:-{{DEFAULT_WORK_DIR}}}"
    fi
    
    echo "Cloning backend repo ${FINAL_BACKEND_REPO}@${FINAL_BACKEND_REF} ..."
    
    # Create work directory first
    mkdir -p "${FINAL_WORK_DIR}"
    
    # Convert to absolute path to avoid issues
    FINAL_WORK_DIR_ABS=$(cd "${FINAL_WORK_DIR}" && pwd)
    REPO_DIR="${FINAL_WORK_DIR_ABS}/go-pan"
    
    # Ensure idempotency: clean before clone
    if [ -d "${REPO_DIR}" ]; then
        echo "Cleaning existing repository: ${REPO_DIR}"
        rm -rf "${REPO_DIR}"
    fi
    
    # Clone repository (fresh clone ensures idempotency)
    git clone --depth 1 --branch "${FINAL_BACKEND_REF}" "${FINAL_BACKEND_REPO}" "${REPO_DIR}"
    
    # Get git commit hash for image tagging
    cd "${REPO_DIR}"
    GIT_COMMIT_HASH=$(git rev-parse --short HEAD)
    GIT_COMMIT_FULL=$(git rev-parse HEAD)
    
    # Save commit info to artifact file
    ARTIFACT_DIR="${FINAL_WORK_DIR_ABS}/.artifacts"
    mkdir -p "${ARTIFACT_DIR}"
    {
        echo "GIT_COMMIT_HASH=${GIT_COMMIT_HASH}"
        echo "GIT_COMMIT_FULL=${GIT_COMMIT_FULL}"
        echo "GIT_BRANCH=${FINAL_BACKEND_REF}"
    } > "${ARTIFACT_DIR}/git-info.env"
    echo "Git commit info saved: ${GIT_COMMIT_HASH} (${GIT_COMMIT_FULL})"
    
    echo "Clone complete: ${REPO_DIR}"

# -----------------------------
# Test-build: Compile Go program locally (for testing only)
# Note: Production builds are handled by Dockerfile
# -----------------------------
test-build BACKEND_REPO='' BACKEND_REF='' WORK_DIR='':
    #!/usr/bin/env bash
    set -e
    
    # Priority: provided args (if not empty) > environment variables > defaults
    if [ -n "$BACKEND_REPO" ]; then
        FINAL_BACKEND_REPO="$BACKEND_REPO"
    else
        FINAL_BACKEND_REPO="${BACKEND_REPO:-{{DEFAULT_BACKEND_REPO}}}"
    fi
    
    if [ -n "$BACKEND_REF" ]; then
        FINAL_BACKEND_REF="$BACKEND_REF"
    else
        FINAL_BACKEND_REF="${BACKEND_REF:-{{DEFAULT_BACKEND_REF}}}"
    fi
    
    if [ -n "$WORK_DIR" ]; then
        FINAL_WORK_DIR="$WORK_DIR"
    else
        FINAL_WORK_DIR="${WORK_DIR:-{{DEFAULT_WORK_DIR}}}"
    fi
    
    # Clone (will clean and re-clone for idempotency)
    just clone BACKEND_REPO="${FINAL_BACKEND_REPO}" BACKEND_REF="${FINAL_BACKEND_REF}" WORK_DIR="${FINAL_WORK_DIR}"
    
    cd "${FINAL_WORK_DIR}/go-pan"
    
    BINARY_NAME="{{BINARY_NAME}}"
    BUILD_OUTPUT="{{BUILD_OUTPUT}}"
    
    echo "Building ${BINARY_NAME} locally (for testing only)..."
    echo "Note: Production builds are handled by Dockerfile during 'just push'"
    
    # Ensure idempotency: clean bin directory before build
    if [ -d "bin" ]; then
        echo "Cleaning bin directory..."
        rm -rf bin
    fi
    mkdir -p bin
    
    CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o "${BUILD_OUTPUT}" main.go
    echo "Build complete: ${PWD}/${BUILD_OUTPUT}"

# -----------------------------
# Push: Build Docker image (compiles inside Docker) and push to registry
# -----------------------------
push BACKEND_REPO='' BACKEND_REF='' WORK_DIR='' REGISTRY='' REGISTRY_NAMESPACE='' BACKEND_IMAGE_NAME='' IMAGE_TAG='':
    #!/usr/bin/env bash
    set -e
    
    # Priority: provided args (if not empty) > environment variables > defaults
    FINAL_REGISTRY="${REGISTRY:-{{DEFAULT_REGISTRY}}}"
    FINAL_REGISTRY_NAMESPACE="${REGISTRY_NAMESPACE:-{{DEFAULT_REGISTRY_NAMESPACE}}}"
    FINAL_BACKEND_IMAGE_NAME="${BACKEND_IMAGE_NAME:-{{DEFAULT_BACKEND_IMAGE_NAME}}}"
    
    # Determine if using remote repo or local code
    # If BACKEND_REPO is provided, use remote; otherwise use local
    if [ -n "${BACKEND_REPO}" ]; then
        # Use remote repository
        FINAL_BACKEND_REPO="${BACKEND_REPO}"
        FINAL_BACKEND_REF="${BACKEND_REF:-{{DEFAULT_BACKEND_REF}}}"
        FINAL_WORK_DIR="${WORK_DIR:-{{DEFAULT_WORK_DIR}}}"
        
        echo "Using remote repository: ${FINAL_BACKEND_REPO}@${FINAL_BACKEND_REF}"
        # Clone (will clean and re-clone for idempotency and get commit hash)
        just clone BACKEND_REPO="${FINAL_BACKEND_REPO}" BACKEND_REF="${FINAL_BACKEND_REF}" WORK_DIR="${FINAL_WORK_DIR}"
        
        # Convert to absolute path to avoid issues after cd
        FINAL_WORK_DIR_ABS=$(cd "${FINAL_WORK_DIR}" && pwd)
        cd "${FINAL_WORK_DIR_ABS}/go-pan"
        
        # Load git commit hash from artifact file
        ARTIFACT_DIR="${FINAL_WORK_DIR_ABS}/.artifacts"
        GIT_INFO_FILE="${ARTIFACT_DIR}/git-info.env"
        if [ -f "${GIT_INFO_FILE}" ]; then
            source "${GIT_INFO_FILE}"
        else
            # Fallback: get commit hash directly
            GIT_COMMIT_HASH=$(git rev-parse --short HEAD)
        fi
    else
        # Use local code (default)
        echo "Using local code (current directory)"
        # Get project root: try to find justfile location, or use current directory
        if [ -f "justfile" ]; then
            PROJECT_ROOT=$(pwd)
        else
            # If justfile is in parent or we're in a subdirectory, find it
            SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" 2>/dev/null && pwd || pwd)"
            if [ -f "${SCRIPT_DIR}/justfile" ]; then
                PROJECT_ROOT="${SCRIPT_DIR}"
            else
                # Fallback: use current directory
                PROJECT_ROOT=$(pwd)
            fi
        fi
        cd "${PROJECT_ROOT}"
        
        # Verify Dockerfile exists
        if [ ! -f "Dockerfile" ]; then
            echo "Error: Dockerfile not found in ${PROJECT_ROOT}" >&2
            echo "  Please ensure you're running this command from the project root directory" >&2
            exit 1
        fi
        
        # Get git commit hash from current directory
        if [ -d ".git" ]; then
            GIT_COMMIT_HASH=$(git rev-parse --short HEAD 2>/dev/null || echo "")
        else
            GIT_COMMIT_HASH=""
            echo "Warning: Not a git repository, cannot get commit hash" >&2
        fi
        
        ARTIFACT_DIR="${PROJECT_ROOT}/.artifacts"
    fi
    
    # Use provided IMAGE_TAG if specified, otherwise use git commit hash, or fallback to timestamp
    if [ -n "$IMAGE_TAG" ]; then
        FINAL_IMAGE_TAG="$IMAGE_TAG"
    elif [ -n "${GIT_COMMIT_HASH}" ]; then
        FINAL_IMAGE_TAG="${GIT_COMMIT_HASH}"
        echo "Using git commit hash as image tag: ${FINAL_IMAGE_TAG}"
    else
        FINAL_IMAGE_TAG=$(date +%Y%m%d%H%M%S)
        echo "Warning: Not a git repository and no IMAGE_TAG provided, using timestamp '${FINAL_IMAGE_TAG}' as image tag"
        echo "  Consider providing IMAGE_TAG parameter for better versioning"
    fi
    
    IMAGE_REPO="${FINAL_REGISTRY}/${FINAL_REGISTRY_NAMESPACE}/${FINAL_BACKEND_IMAGE_NAME}"
    IMAGE_FULL="${IMAGE_REPO}:${FINAL_IMAGE_TAG}"
    
    echo "Building Docker image: ${IMAGE_FULL}"
    echo "  Note: Compilation happens inside Docker (multi-stage build)"
    echo "  REGISTRY=${FINAL_REGISTRY}"
    echo "  REGISTRY_NAMESPACE=${FINAL_REGISTRY_NAMESPACE}"
    echo "  BACKEND_IMAGE_NAME=${FINAL_BACKEND_IMAGE_NAME}"
    echo "  IMAGE_TAG=${FINAL_IMAGE_TAG}"
    
    # Login to registry if credentials provided
    if [ -n "${REGISTRY_USER:-}" ] && [ -n "${REGISTRY_PASSWORD:-}" ]; then
        echo "Logging in to registry ${FINAL_REGISTRY}..."
        echo "${REGISTRY_PASSWORD}" | docker login "${FINAL_REGISTRY}" -u "${REGISTRY_USER}" --password-stdin
    else
        echo "No REGISTRY_USER/REGISTRY_PASSWORD provided; skipping docker login."
    fi
    
    # Build image (Dockerfile handles compilation)
    # Using --no-cache to ensure idempotency (fresh build every time)
    # Ensure we're in the correct directory before building
    BUILD_DIR=$(pwd)
    if [ ! -f "Dockerfile" ]; then
        echo "Error: Dockerfile not found in ${BUILD_DIR}" >&2
        exit 1
    fi
    echo "Building Docker image (this will compile the code inside the container)..."
    echo "  Build directory: ${BUILD_DIR}"
    docker build --no-cache -t "${IMAGE_FULL}" .
    
    # Push image
    echo "Pushing ${IMAGE_FULL}..."
    PUSH_OUTPUT=$(docker push "${IMAGE_FULL}" 2>&1)
    PUSH_EXIT_CODE=$?
    
    if [ $PUSH_EXIT_CODE -ne 0 ]; then
        echo "Error: Failed to push image ${IMAGE_FULL}" >&2
        echo "$PUSH_OUTPUT" >&2
        exit 1
    fi
    
    # Verify push was successful by checking for digest in output
    if echo "$PUSH_OUTPUT" | grep -q "digest:"; then
        echo "Image pushed successfully: ${IMAGE_FULL}"
        DIGEST=$(echo "$PUSH_OUTPUT" | grep "digest:" | sed 's/.*digest: //' | awk '{print $1}')
        echo "  Digest: ${DIGEST}"
    else
        echo "Warning: Could not find digest in push output, but push command succeeded"
        echo "  Assuming image was pushed successfully"
    fi
    
    # Also push latest tag if not already latest
    if [ "${FINAL_IMAGE_TAG}" != "latest" ]; then
        docker tag "${IMAGE_FULL}" "${IMAGE_REPO}:latest"
        docker push "${IMAGE_REPO}:latest"
        echo "Also pushed ${IMAGE_REPO}:latest"
    fi
    
    # Save image info to artifact file for deploy command
    mkdir -p "${ARTIFACT_DIR}"
    {
        echo "IMAGE_REPO=${IMAGE_REPO}"
        echo "IMAGE_TAG=${FINAL_IMAGE_TAG}"
        echo "IMAGE_FULL=${IMAGE_FULL}"
        echo "GIT_COMMIT_HASH=${GIT_COMMIT_HASH}"
    } > "${ARTIFACT_DIR}/image-info.env"
    echo "Image info saved to ${ARTIFACT_DIR}/image-info.env"
    echo "  Image: ${IMAGE_FULL}"
    if [ -n "${GIT_COMMIT_HASH}" ]; then
        echo "  Git commit: ${GIT_COMMIT_HASH}"
    fi
    
    echo "Push complete: ${IMAGE_FULL}"

# -----------------------------
# Deploy: Deploy to Kubernetes using Helm
# -----------------------------
deploy BACKEND_REPO='' BACKEND_REF='' WORK_DIR='' REGISTRY='' REGISTRY_NAMESPACE='' BACKEND_IMAGE_NAME='' IMAGE_TAG='' K8S_NAMESPACE='' RELEASE_BACKEND='' HELM_CHART_PATH='' KUBECONFIG_PATH='':
    #!/usr/bin/env bash
    set -e
    
    # Priority: provided args (if not empty) > environment variables > defaults
    FINAL_REGISTRY="${REGISTRY:-{{DEFAULT_REGISTRY}}}"
    FINAL_REGISTRY_NAMESPACE="${REGISTRY_NAMESPACE:-{{DEFAULT_REGISTRY_NAMESPACE}}}"
    FINAL_BACKEND_IMAGE_NAME="${BACKEND_IMAGE_NAME:-{{DEFAULT_BACKEND_IMAGE_NAME}}}"
    FINAL_K8S_NAMESPACE="${K8S_NAMESPACE:-{{DEFAULT_K8S_NAMESPACE}}}"
    FINAL_RELEASE_BACKEND="${RELEASE_BACKEND:-{{DEFAULT_RELEASE_BACKEND}}}"
    FINAL_HELM_CHART_PATH="${HELM_CHART_PATH:-{{DEFAULT_HELM_CHART_PATH}}}"
    FINAL_KUBECONFIG_PATH="${KUBECONFIG_PATH:-{{DEFAULT_KUBECONFIG_PATH}}}"
    
    # Determine if using remote repo or local code
    # If BACKEND_REPO is provided, use remote; otherwise use local
    if [ -n "${BACKEND_REPO}" ]; then
        # Use remote repository
        FINAL_BACKEND_REPO="${BACKEND_REPO}"
        FINAL_BACKEND_REF="${BACKEND_REF:-{{DEFAULT_BACKEND_REF}}}"
        FINAL_WORK_DIR="${WORK_DIR:-{{DEFAULT_WORK_DIR}}}"
        
        echo "Using remote repository: ${FINAL_BACKEND_REPO}@${FINAL_BACKEND_REF}"
        # Clone (will clean and re-clone for idempotency and get commit hash)
        just clone BACKEND_REPO="${FINAL_BACKEND_REPO}" BACKEND_REF="${FINAL_BACKEND_REF}" WORK_DIR="${FINAL_WORK_DIR}"
        
        # Convert to absolute path to avoid issues after cd
        FINAL_WORK_DIR_ABS=$(cd "${FINAL_WORK_DIR}" && pwd)
        cd "${FINAL_WORK_DIR_ABS}/go-pan"
        
        ARTIFACT_FILE="${FINAL_WORK_DIR_ABS}/.artifacts/image-info.env"
        GIT_INFO_FILE="${FINAL_WORK_DIR_ABS}/.artifacts/git-info.env"
    else
        # Use local code (default)
        echo "Using local code (current directory)"
        # Get project root: try to find justfile location, or use current directory
        if [ -f "justfile" ]; then
            PROJECT_ROOT=$(pwd)
        else
            # If justfile is in parent or we're in a subdirectory, find it
            SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" 2>/dev/null && pwd || pwd)"
            if [ -f "${SCRIPT_DIR}/justfile" ]; then
                PROJECT_ROOT="${SCRIPT_DIR}"
            else
                # Fallback: use current directory
                PROJECT_ROOT=$(pwd)
            fi
        fi
        cd "${PROJECT_ROOT}"
        
        ARTIFACT_FILE="${PROJECT_ROOT}/.artifacts/image-info.env"
        GIT_INFO_FILE="${PROJECT_ROOT}/.artifacts/git-info.env"
    fi
    
    IMAGE_REPO="${FINAL_REGISTRY}/${FINAL_REGISTRY_NAMESPACE}/${FINAL_BACKEND_IMAGE_NAME}"
    
    # Try to load image info from artifact file (if push was run before)
    if [ -f "${ARTIFACT_FILE}" ]; then
        echo "Found image artifact file, loading image info..."
        source "${ARTIFACT_FILE}"
        # Ensure FINAL_IMAGE_TAG is set from artifact file
        FINAL_IMAGE_TAG="${IMAGE_TAG}"
        echo "Using image from artifact: ${IMAGE_FULL}"
        echo "  Image tag: ${FINAL_IMAGE_TAG}"
        if [ -n "${GIT_COMMIT_HASH}" ]; then
            echo "  Git commit: ${GIT_COMMIT_HASH}"
        fi
        echo "  (This ensures the same image that was pushed is deployed)"
    else
        # Load git commit hash
        if [ -f "${GIT_INFO_FILE}" ]; then
            source "${GIT_INFO_FILE}"
        elif [ -d ".git" ]; then
            GIT_COMMIT_HASH=$(git rev-parse --short HEAD 2>/dev/null || echo "")
        else
            GIT_COMMIT_HASH=""
        fi
        
        # Use provided IMAGE_TAG if specified, otherwise use git commit hash, or fallback to timestamp
        if [ -n "$IMAGE_TAG" ]; then
            FINAL_IMAGE_TAG="$IMAGE_TAG"
        elif [ -n "${GIT_COMMIT_HASH}" ]; then
            FINAL_IMAGE_TAG="${GIT_COMMIT_HASH}"
            echo "Using git commit hash as image tag: ${FINAL_IMAGE_TAG}"
        else
            FINAL_IMAGE_TAG=$(date +%Y%m%d%H%M%S)
            echo "Warning: Not a git repository and no IMAGE_TAG provided, using timestamp '${FINAL_IMAGE_TAG}' as image tag"
            echo "  Consider providing IMAGE_TAG parameter for better versioning"
        fi
        
        IMAGE_FULL="${IMAGE_REPO}:${FINAL_IMAGE_TAG}"
        echo "Warning: No image artifact file found at ${ARTIFACT_FILE}"
        echo "  Make sure to run 'just push' before 'just deploy', or use 'just all'"
        echo "  Proceeding with image: ${IMAGE_FULL}"
    fi
    
    # Validate that FINAL_IMAGE_TAG is not empty
    if [ -z "${FINAL_IMAGE_TAG}" ]; then
        echo "Error: IMAGE_TAG is empty! Cannot deploy." >&2
        echo "  Please run 'just push' first, or provide IMAGE_TAG parameter." >&2
        exit 1
    fi
    
    # Verify image exists in registry before deploying
    # Try manifest inspect first, but don't fail if it's not supported
    echo "Verifying image exists in registry: ${IMAGE_FULL}..."
    if docker manifest inspect "${IMAGE_FULL}" >/dev/null 2>&1; then
        echo "Image verified in registry: ${IMAGE_FULL}"
    else
        echo "Note: Could not verify image via manifest inspect (may not be supported by registry)"
        echo "  Proceeding with deployment - K8s will verify image availability during pull"
    fi
    
    echo "Deploying to Kubernetes..."
    echo "  Namespace: ${FINAL_K8S_NAMESPACE}"
    echo "  Release: ${FINAL_RELEASE_BACKEND}"
    echo "  Image Repository: ${IMAGE_REPO}"
    echo "  Image Tag: ${FINAL_IMAGE_TAG}"
    echo "  Full Image: ${IMAGE_FULL}"
    echo "  Chart: ${FINAL_HELM_CHART_PATH}"
    
    # Double-check that FINAL_IMAGE_TAG is not empty
    if [ -z "${FINAL_IMAGE_TAG}" ]; then
        echo "Error: FINAL_IMAGE_TAG is empty! Cannot proceed with deployment." >&2
        exit 1
    fi
    
    # Check if helm is available
    command -v helm >/dev/null 2>&1 || { echo "Error: helm not found" >&2; exit 1; }
    
    # Expand kubeconfig path
    KUBECONFIG_EXPANDED=$(eval echo "${FINAL_KUBECONFIG_PATH}")
    if [ ! -f "${KUBECONFIG_EXPANDED}" ]; then
        echo "Error: Kubeconfig not found at ${KUBECONFIG_EXPANDED}" >&2
        exit 1
    fi
    export KUBECONFIG="${KUBECONFIG_EXPANDED}"
    
    # Verify cluster connection
    helm version
    
    # Resolve Helm chart path to absolute path if it's relative
    if [ -n "${BACKEND_REPO}" ]; then
        # Using remote repo: chart path is relative to cloned repo
        HELM_CHART_ABS="${FINAL_HELM_CHART_PATH}"
    else
        # Using local code: resolve chart path relative to project root
        if [ "${FINAL_HELM_CHART_PATH#/}" = "${FINAL_HELM_CHART_PATH}" ]; then
            # Relative path
            HELM_CHART_ABS="${PROJECT_ROOT}/${FINAL_HELM_CHART_PATH}"
        else
            # Absolute path
            HELM_CHART_ABS="${FINAL_HELM_CHART_PATH}"
        fi
    fi
    
    # Verify Helm chart exists
    if [ ! -d "${HELM_CHART_ABS}" ]; then
        echo "Error: Helm chart not found at ${HELM_CHART_ABS}" >&2
        echo "  Project root: ${PROJECT_ROOT}" >&2
        echo "  Chart path: ${FINAL_HELM_CHART_PATH}" >&2
        exit 1
    fi
    
    # Deploy with Helm (upgrade --install is idempotent)
    # Use IMAGE_FULL to ensure exact image version is deployed
    echo "Executing helm upgrade --install with:"
    echo "  image.repository=${IMAGE_REPO}"
    echo "  image.tag=${FINAL_IMAGE_TAG}"
    echo "  chart path: ${HELM_CHART_ABS}"
    helm upgrade --install "${FINAL_RELEASE_BACKEND}" "${HELM_CHART_ABS}" \
        --namespace "${FINAL_K8S_NAMESPACE}" \
        --create-namespace \
        --set image.repository="${IMAGE_REPO}" \
        --set image.tag="${FINAL_IMAGE_TAG}" \
        --server-side auto \
        --force-conflicts \
        --wait
    
    # Verify deployment is using the correct image using Helm
    echo "Verifying deployment..."
    DEPLOYED_IMAGE=$(helm get manifest "${FINAL_RELEASE_BACKEND}" -n "${FINAL_K8S_NAMESPACE}" 2>/dev/null | grep -E "^\s+image:" | head -1 | sed -E 's/^\s+image:\s*["'\'']?([^"'\'']+)["'\'']?/\1/' || echo "")
    
    if [ -n "${DEPLOYED_IMAGE}" ]; then
        echo "Deployed image: ${DEPLOYED_IMAGE}"
        if [ "${DEPLOYED_IMAGE}" != "${IMAGE_FULL}" ]; then
            echo "Warning: Deployed image (${DEPLOYED_IMAGE}) differs from expected (${IMAGE_FULL})"
        else
            echo "✓ Image version verified: ${IMAGE_FULL}"
        fi
    else
        echo "Note: Could not verify deployed image (deployment may not exist yet)"
    fi
    
    echo "Deployment complete!"

# -----------------------------
# All: Run push and deploy in sequence (using local code by default, or remote if BACKEND_REPO is provided)
# Note: Compilation is handled by Dockerfile during push
# -----------------------------
all BACKEND_REPO='' BACKEND_REF='' WORK_DIR='' REGISTRY='' REGISTRY_NAMESPACE='' BACKEND_IMAGE_NAME='' IMAGE_TAG='' K8S_NAMESPACE='' RELEASE_BACKEND='' HELM_CHART_PATH='' KUBECONFIG_PATH='':
    #!/usr/bin/env bash
    set -e
    # Note: IMAGE_TAG is optional - if not provided, git commit hash will be used automatically (or timestamp if not a git repo)
    just push BACKEND_REPO="$BACKEND_REPO" BACKEND_REF="$BACKEND_REF" WORK_DIR="$WORK_DIR" REGISTRY="$REGISTRY" REGISTRY_NAMESPACE="$REGISTRY_NAMESPACE" BACKEND_IMAGE_NAME="$BACKEND_IMAGE_NAME" IMAGE_TAG="$IMAGE_TAG"
    just deploy BACKEND_REPO="$BACKEND_REPO" BACKEND_REF="$BACKEND_REF" WORK_DIR="$WORK_DIR" REGISTRY="$REGISTRY" REGISTRY_NAMESPACE="$REGISTRY_NAMESPACE" BACKEND_IMAGE_NAME="$BACKEND_IMAGE_NAME" IMAGE_TAG="$IMAGE_TAG" K8S_NAMESPACE="$K8S_NAMESPACE" RELEASE_BACKEND="$RELEASE_BACKEND" HELM_CHART_PATH="$HELM_CHART_PATH" KUBECONFIG_PATH="$KUBECONFIG_PATH"

# -----------------------------
# Clean: Remove work directory, artifacts, and optionally Docker images
# -----------------------------
clean WORK_DIR='' REGISTRY='' REGISTRY_NAMESPACE='' BACKEND_IMAGE_NAME='' CLEAN_IMAGES='false':
    #!/usr/bin/env bash
    set -e
    
    if [ -n "$WORK_DIR" ]; then
        FINAL_WORK_DIR="$WORK_DIR"
    else
        FINAL_WORK_DIR="${WORK_DIR:-{{DEFAULT_WORK_DIR}}}"
    fi
    
    if [ -n "$REGISTRY" ]; then
        FINAL_REGISTRY="$REGISTRY"
    else
        FINAL_REGISTRY="${REGISTRY:-{{DEFAULT_REGISTRY}}}"
    fi
    
    if [ -n "$REGISTRY_NAMESPACE" ]; then
        FINAL_REGISTRY_NAMESPACE="$REGISTRY_NAMESPACE"
    else
        FINAL_REGISTRY_NAMESPACE="${REGISTRY_NAMESPACE:-{{DEFAULT_REGISTRY_NAMESPACE}}}"
    fi
    
    if [ -n "$BACKEND_IMAGE_NAME" ]; then
        FINAL_BACKEND_IMAGE_NAME="$BACKEND_IMAGE_NAME"
    else
        FINAL_BACKEND_IMAGE_NAME="${BACKEND_IMAGE_NAME:-{{DEFAULT_BACKEND_IMAGE_NAME}}}"
    fi
    
    # Clean work directory
    if [ -d "${FINAL_WORK_DIR}" ]; then
        echo "Removing work directory: ${FINAL_WORK_DIR}"
        rm -rf "${FINAL_WORK_DIR}"
        echo "Work directory removed"
    else
        echo "Work directory does not exist: ${FINAL_WORK_DIR}"
    fi
    
    # Clean local Docker images if requested
    if [ "${CLEAN_IMAGES}" = "true" ] || [ "${CLEAN_IMAGES}" = "1" ]; then
        echo "Cleaning local Docker images..."
        IMAGE_PATTERN="${FINAL_REGISTRY}/${FINAL_REGISTRY_NAMESPACE}/${FINAL_BACKEND_IMAGE_NAME}"
        # Find and remove matching images
        # Use docker images output and parse with awk to avoid justfile variable syntax conflicts
        docker images "${IMAGE_PATTERN}" 2>/dev/null | awk 'NR>1 {print $1":"$2}' | while read -r img; do
            if [ -n "${img}" ] && [ "${img}" != "REPOSITORY:TAG" ]; then
                echo "  Removing image: ${img}"
                docker rmi "${img}" 2>/dev/null || true
            fi
        done
        echo "Docker images cleaned"
    fi
    
    echo "Clean complete"
